# -*- coding:utf-8 -*-
import json
import threading
from channels.generic.websocket import AsyncWebsocketConsumer
import logging

from Apps.UiTest.runTest.runUiTest import RunUiTest
from Apps.common.interface.interface import RunInterfaceRequest

logger = logging.getLogger("django")


class UserSkView(AsyncWebsocketConsumer):

    def __init__(self, *args, **kwargs):
        super().__init__(args, kwargs)
        self.requestId = None
        self.request_group = None

    async def connect(self):
        self.requestId = self.scope["url_route"]["kwargs"].get("pk")
        self.request_group = f"user_{self.requestId}"

        await self.channel_layer.group_add(self.request_group, self.channel_name)

        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.request_group, self.channel_name)

    # 收到请求数据
    async def receive(self, text_data):
        if text_data == "ping":
            # 心跳返回
            heartbeat_data = {"type": "heartbeat", "data": "peng"}
            await self.channel_layer.group_send(
                self.request_group, {"type": "send.result", "message": heartbeat_data}
            )

    # 返回请求结果
    async def send_result(self, event):
        message = event["message"]

        await self.send(text_data=json.dumps(message))

# await self.channel_layer.group_send(
#             self.request_group, {"type": "send.result", "message": message}
#         )
